package com.wanhai.zkbase.report;

import com.wanhai.util.report.ReportBean;
import com.wanhai.util.report.ReportUtil;
import com.wanhai.zkbase.core.WHL_BaseVM;
import com.wanhai.zkbase.util.SelectItem;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Div;
import org.zkoss.zul.Panel;

/**
 *
 * @author Richard Shih
 */
public abstract class ReportVM extends WHL_BaseVM {

    protected String printType = "A1";
    protected String jobName;
    protected String isJob = "N";
    protected String schedule;
    protected List printList = null;
    protected String printId;
    protected int printCopies = 0;
    protected List faxList;
    protected String faxFrom;
    protected String faxTo;
    protected String faxCC;
    protected String faxBCC;
    protected String faxSubject;
    protected String faxContent;
    protected String faxId;
    protected String mailFrom;
    protected String mailTo;
    protected String mailCC;
    protected String mailBCC;
    protected String mailSubject;
    protected String mailContent;
    protected String fileName;
    protected String rptPath;
    protected String fileType = "pdf";
    protected String CR_URL;
    protected String rowDataURL;
    protected String rowDataServlet;
    public boolean disabledPrint;
    protected String reportProp;
    protected String reportDS;
    protected String defaultPrint;
    protected ReportUtil ru = new ReportUtil();
    /*components from zul page*/
    @Wire
    Div fileSection;
    @Wire
    Div printSection;
    @Wire
    Div mailSection;
    @Wire
    Div faxSection;
    @Wire
    Div jobSection;
    @Wire
    Panel pnlRPParam;

    @Init(superclass = true)
    public void Init() {

        initValues();
        fetchPrinterList();
        fetchFaxList();
    }

    //<editor-fold defaultstate="collapse" desc="commands">
    @Command("onJobTypeChange")
    public void onJobTypeChange() {
        jobSection.setVisible("Y".equals(getIsJob()));
    }

    @Command("onPrintTypeChange")
    public void onPrintTypeChange() {
        fileSection.setVisible(false);
        printSection.setVisible(false);
        faxSection.setVisible(false);
        mailSection.setVisible(false);
        if ("A1".equals(getPrintType())) {
            fileSection.setVisible(true);
            Clients.scrollIntoView(fileSection);
        } else if ("A".equals(getPrintType())) {
            printSection.setVisible(true);
            Clients.scrollIntoView(printSection);
        } else if ("B".equals(getPrintType())) {
            faxSection.setVisible(true);
            Clients.scrollIntoView(faxSection);
        } else if ("C".equals(getPrintType())) {
            mailSection.setVisible(true);
            Clients.scrollIntoView(mailSection);
        }
        pnlRPParam.invalidate();
    }
    //</editor-fold>
    //<editor-fold defaultstate="collapse" desc="action methods">

    /**
     * create report for print / file (print_type='A1' or 'A')
     *
     * @param rpBean {@link com.wanhai.util.report.ReportBean ReportBean}, use
     * to carry report information
     * @param qryConds query conditions (use to insert into was5012)
     * @return report_id
     * @throws Exception
     */
    protected BigDecimal printAction(ReportBean rpBean, HashMap qryConds) throws Exception {
        if (printId == null || printId.isEmpty()) {
            printId = ((SelectItem) this.printList.get(0)).getValue();
        }
        if ("Y".equals(isJob)) {
            return rpBean.createPrinterJob(getJobName(), new java.math.BigDecimal(printId), printCopies, getFileName(), qryConds, getRowDataURL(), getCR_URL(), getRptPath(), getScheduleDate());
        } else {
            return rpBean.createPrinter(getJobName(), new java.math.BigDecimal(printId), printCopies, getFileName(), qryConds, getRowDataURL(), getCR_URL(), getRptPath());
        }
    }

    /**
     * create report for mail (print_type='C')
     *
     * @param rpBean {@link com.wanhai.util.report.ReportBean ReportBean}, use
     * to carry report information
     * @param qryConds query conditions (use to insert into was5012)
     * @return report_id
     * @throws Exception
     */
    protected BigDecimal mailAction(ReportBean rpBean, HashMap qryConds) throws Exception {
        if ("Y".equals(isJob)) {
            return rpBean.createMailJob(getJobName(), getFileName(), qryConds, getRowDataURL(), getCR_URL(), getRptPath(), getScheduleDate());
        } else {
            return rpBean.createMail(getJobName(), getFileName(), qryConds, getRowDataURL(), getCR_URL(), getRptPath());
        }
    }

    /**
     * create report for fax (print_type='B')
     *
     * @param rpBean {@link com.wanhai.util.report.ReportBean ReportBean}, use
     * to carry report information
     * @param qryConds query conditions (use to insert into was5012)
     * @return report_id
     * @throws Exception
     */
    protected BigDecimal faxAction(ReportBean rpBean, HashMap qryConds) throws Exception {
        if ("Y".equals(isJob)) {
            return rpBean.createFaxJob(getJobName(), getFileName(), getFaxId(), qryConds, getRowDataURL(), getCR_URL(), getRptPath(), getScheduleDate());
        } else {
            return rpBean.createFax(getJobName(), getFileName(), getFaxId(), qryConds, getRowDataURL(), getCR_URL(), getRptPath());
        }
    }

    /**
     * report trigger method<br>
     * 子類別透過呼叫此方法啓動report機制
     *
     * @param rpBean {@link com.wanhai.util.report.ReportBean ReportBean}, use
     * to carry report information
     * @throws Exception
     */
    public BigDecimal triggerPrint(ReportBean rpBean) throws Exception {
        if (this.getUserBean().getIsInternetUser()) {
            rpBean.setIS_INTERNET("Y");
        }
        try {
            HashMap conds = (HashMap) getRptQryConditions();
            if (printType != null && printType.startsWith("A")) {
                return printAction(rpBean, conds);
            } else if ("B".equals(printType)) {
                return faxAction(rpBean, conds);
            } else if ("C".equals(printType)) {
                return mailAction(rpBean, conds);
            }
        } catch (Exception ex) {
            //log error msg or notice report admin here when report creation fail
            logger.error(ex.getMessage(), ex);
            throw ex;
        }
        return null;
    }

    /**
     * get all query conditions from this report<br>
     * 所有子類別必須實作此方法並回傳前端頁面上的查詢條件
     *
     * @return
     */
    protected abstract Map<String, Object> getRptQryConditions();
    //</editor-fold>
    //<editor-fold defaultstate="collapse" desc="getter & setter">

    public String getReportProp() {
        return reportProp;
    }

    public void setReportProp(String reportProp) {
        this.reportProp = reportProp;
    }

    public String getReportDS() {
        return reportDS;
    }

    public void setReportDS(String reportDS) {
        this.reportDS = reportDS;
    }

    public List getPrintList() {
        return printList;
    }

    public void setPrintList(List printList) {
        this.printList = printList;
    }

    public boolean isDisabledPrint() {
        return disabledPrint;
    }

    public void setDisabledPrint(boolean disabledPrint) {
        this.disabledPrint = disabledPrint;
    }

    public List getFaxList() {
        return faxList;
    }

    public void setFaxList(List faxList) {
        this.faxList = faxList;
    }

    public void setSchedule(String schedule) {
        this.schedule = schedule;
    }

    public String getSchedule() {
        return schedule;
    }

    public Date getScheduleDate() throws ParseException {
        Date dateJob = null;
        if (getSchedule() != null && !getSchedule().equals("")) {
            DateFormat dfm = new java.text.SimpleDateFormat("yyyyMMdd HH:mm:ss");
            dateJob = dfm.parse(getSchedule());
        }
        return dateJob;
    }

    public String getPrintType() {
        return printType;
    }

    public void setPrintType(String printType) {
        this.printType = printType;
    }

    public String getJobName() {
        return jobName;
    }

    public void setJobName(String jobName) {
        this.jobName = jobName;
    }

    public String getIsJob() {
        return isJob;
    }

    public void setIsJob(String isJob) {
        this.isJob = isJob;
    }

    public String getPrintId() {
        return printId;
    }

    public void setPrintId(String printId) {
        this.printId = printId;
    }

    public int getPrintCopies() {
        return printCopies;
    }

    public void setPrintCopies(int printCopies) {
        this.printCopies = printCopies;
    }

    public String getFaxId() {
        return faxId;
    }

    public void setFaxId(String faxId) {
        this.faxId = faxId;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getRptPath() {
        return rptPath;
    }

    public void setRptPath(String rptPath) {
        this.rptPath = rptPath;
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }

    public String getCR_URL() {
        return CR_URL;
    }

    public void setCR_URL(String CR_URL) {
        this.CR_URL = CR_URL;
    }

    public String getRowDataURL() {
        rowDataURL = getURLPath() + getRowDataServlet();
        return rowDataURL;
    }

    public void setRowDataURL(String rowDataURL) {
        this.rowDataURL = rowDataURL;
    }

    public String getRowDataServlet() {
        return rowDataServlet;
    }

    public void setRowDataServlet(String rowDataServlet) {
        this.rowDataServlet = rowDataServlet;
    }

    public String getDefaultPrint() {
        return defaultPrint;
    }

    public void setDefaultPrint(String defaultPrint) {
        this.defaultPrint = defaultPrint;
    }

    public List getPrinterList() {
        return printList;
    }

    public String getFaxFrom() {
        return faxFrom;
    }

    public void setFaxFrom(String faxFrom) {
        this.faxFrom = faxFrom;
    }

    public String getFaxTo() {
        return faxTo;
    }

    public void setFaxTo(String faxTo) {
        this.faxTo = faxTo;
    }

    public String getFaxCC() {
        return faxCC;
    }

    public void setFaxCC(String faxCC) {
        this.faxCC = faxCC;
    }

    public String getFaxBCC() {
        return faxBCC;
    }

    public void setFaxBCC(String faxBCC) {
        this.faxBCC = faxBCC;
    }

    public String getFaxSubject() {
        return faxSubject;
    }

    public void setFaxSubject(String faxSubject) {
        this.faxSubject = faxSubject;
    }

    public String getFaxContent() {
        return faxContent;
    }

    public void setFaxContent(String faxContent) {
        this.faxContent = faxContent;
    }

    public String getMailFrom() {
        return mailFrom;
    }

    public void setMailFrom(String mailFrom) {
        this.mailFrom = mailFrom;
    }

    public String getMailTo() {
        return mailTo;
    }

    public void setMailTo(String mailTo) {
        this.mailTo = mailTo;
    }

    public String getMailCC() {
        return mailCC;
    }

    public void setMailCC(String mailCC) {
        this.mailCC = mailCC;
    }

    public String getMailBCC() {
        return mailBCC;
    }

    public void setMailBCC(String mailBCC) {
        this.mailBCC = mailBCC;
    }

    public String getMailSubject() {
        return mailSubject;
    }

    public void setMailSubject(String mailSubject) {
        this.mailSubject = mailSubject;
    }

    public String getMailContent() {
        return mailContent;
    }

    public void setMailContent(String mailContent) {
        this.mailContent = mailContent;
    }

    //</editor-fold>
    //<editor-fold defaultstate="collapse" desc="tool methods">
    private void initValues() {
        String strReportProp = this.getUserBean().getCompanyCode() + "_" + configUtil.getSrvLocation();
        this.setReportProp(strReportProp);
        logger.debug("Report Prop: " + strReportProp);

        String rDS = configUtil.getJNDIByTNS(strReportProp);
        this.setReportDS(rDS);
        logger.debug("Report DS: " + rDS);
    }

    private String getURLPath() {
        HttpServletRequest request = (HttpServletRequest) Executions.getCurrent().getNativeRequest();
        String _URLPath = request.getScheme() + "://";
        _URLPath += request.getServerName() + ":";
        _URLPath += request.getServerPort();
        _URLPath += request.getContextPath() + "/";
        return _URLPath;
    }

    protected void fetchPrinterList() {
        ReportUtil reportU = new ReportUtil();
        String[][] activePrintlIst = reportU.officeDefaultPrint(this.getUserBean().getOfficeCode(), this.reportDS);
        setPrintList(new ArrayList());
        if (activePrintlIst.length > 0 && activePrintlIst[0][1].equals("@")) {
            printList.add(new SelectItem(activePrintlIst[0][0], activePrintlIst[0][1]));
            setDisabledPrint(true);
        } else {
            printList.add(new SelectItem("0", "NONE"));
            setDisabledPrint(true);
        }
    }

    protected void fetchPrinterListByUser() {
        ReportUtil reportU = new ReportUtil();
        setPrintList(new ArrayList());
        if (!this.getUserBean().getIsInternetUser()) {
            String[][] activePrintlIst = reportU.activePrintList(this.getUserBean().getUserCode(), this.reportDS);
            String strPrintId = activePrintlIst[0][0];
            if (activePrintlIst.length > 0 && !strPrintId.equals("")) {
                setDisabledPrint(false);
                for (int i = 0; i < activePrintlIst.length; i++) {
                    printList.add(new SelectItem(activePrintlIst[i][0], activePrintlIst[i][1]));
                }
            } else {
                printList.add(new SelectItem("0", "NONE"));
                setDisabledPrint(true);
            }
        } else {
            printList.add(new SelectItem("0", "NONE"));
            setDisabledPrint(true);
        }
    }

    protected List fetchFaxList() {
        ReportUtil reportU = new ReportUtil();
        String[][] activePrintlIst = reportU.activeFaxListAll(this.getUserBean().getOfficeCode(), this.reportDS);
        setFaxList(new ArrayList());
        for (int i = 0; i < activePrintlIst.length; i++) {
            faxList.add(new SelectItem(activePrintlIst[i][0], activePrintlIst[i][1]));
        }
        return faxList;
    }
    //</editor-fold>
}
